﻿using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System;
using System.Collections;

namespace MyAssetBundles {
    public class UnpackFolderProgress : FolderProgress {
        protected override void ShowProgress ()
        {
            string info = string.Format("process number: {0}, total number: {1}, progress: {2}%", target.processNum, target.totalNum, target.progress * 100);
            ShowProgress("Unpack", info);
        }
    }

    public class UnpackFolder : BaseFolder, IFolder {
        public List<string> assetBundlesNameList = new List<string>();
        public void Generate (string path, IFolderProgress progress)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            if (!dir.Exists) dir.Create();
            if (Count == 0) return;
            SetProgress(progress, Count);

            var etor = GetEnumerator();
            etor.MoveNext();
            FileInfo file = new FileInfo(etor.Current.Value.Path);
            FileStream fStream = file.Open(FileMode.Open, FileAccess.Read);

            int processNum = 0;
            etor = GetEnumerator();
            while (etor.MoveNext())
            {
                Debug.Log("unpack files, process number:  " + processNum);
                MyFileInfo myFile = etor.Current.Value;
                string filePath = MyAssetBundlesUtil.PathCombine(path, myFile.Name);
                SetFileNameCurr(myFile.Name);
                SetProcessNum(processNum++);
                DirectoryInfo dirTemp = new DirectoryInfo(Path.GetDirectoryName(filePath));
                if (!dirTemp.Exists) dirTemp.Create();
                FileInfo fileInfo = new FileInfo(filePath);
                FileStream writeFile = fileInfo.Create();
                if (fStream.Length >= myFile.DataByteLength + myFile.DataCursorStart)
                {
                    byte[] data = new byte[myFile.DataByteLength];
                    fStream.Seek(myFile.DataCursorStart, SeekOrigin.Begin);
                    fStream.Read(data, 0, myFile.DataByteLength);
                    writeFile.Write(data, 0, myFile.DataByteLength);
                }
                writeFile.Flush();
                writeFile.Close();
                assetBundlesNameList.Add(myFile.Name);
                Debug.Log(" " + filePath);
            }

            fStream.Close();
            fStream = null;
        }
    }
}
